把 AI 寫的單執行緒 Code 丟到 Production,後果八成是撞成一灘肉泥。
如果你的產品只有你自己一個人在用,那 AI 寫出來的 Code 確實堪稱完美。但現實是,大廠的產線每天要扛幾百萬個 Request。AI 最致命的盲區,就是它根本沒有「高併發(Concurrency)」跟「執行緒安全(Thread-Safety)」的概念。
在寫 Code 時,AI 為了用最少的行數把功能實作出來,最喜歡:大量使用模組層級的變數(Global State),或者在 Class 裡面宣告不安全的共用屬性。
舉個最常見的例子
# Mutable Default Argument
def fetch_user_data(user_id, cache={}):
if user_id not in cache:
cache[user_id] = db.get_user(user_id)
return cache[user_id]
在 Local 端測試,打一兩個 Request,看起來超棒,快取有發揮作用。結果一推到 Production,用 Gunicorn 開了多個 Worker,加上非同步的高併發衝擊,整個 Memory 瞬間亂竄。A 使用者登入,結果畫面上顯示 B 使用者的個資
想防堵這種高併發災難,不能只靠寫 Unit Test,因為常規的 Unit Test 都是單執行緒(Single-thread)在跑的,根本測不出 Race Condition。
我們可以在兩個層面上建立防呆機制:靜態分析封殺,以及動態壓力測試。
# pyproject.toml
[tool.ruff]
# 開啟 B (Bugbear) 規則,專門抓 AI 寫的潛在地雷
select = ["E", "F", "B"]
# B006: 絕對不允許使用 list, dict 等可變物件作為 Default Argument
# B008: 絕對不允許在 function 參數中執行 function call
name: Load Test Gate
on: [pull_request]
jobs:
k6_stress_test:
runs-on: ubuntu-latest
steps:
- name: 40workers
run: gunicorn app.main:app -w 4 --daemon
- name: 100 users
run: k6 run tests/load/concurrent_test.js